﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using ConsolidationTool.Common;

namespace ConsolidationTool.WebParts
{
    /*
     * List : Brochure Report Configuration(BRC)   --make a list for brochure report config 
     * List Fields: Title:identity for each report name , Description: what's this report , Mapping: mapping for each report , Category: for some group type report
     * GroupMapping: the mapping for output excel document exmple: Group1:H|12,Group2:H|15
     * AdditionOutput: the mapping for addition data, exmple: H13:_CurrentMonth_,J23:_YTD_,J24:_IN Currency_
     * 
     * the group:table should be a json array group like this : []
     * {id:0, title:"", group:"", equ:"", list:"", fields:[] }
     * Description for "fields" {name:"", from:[] }
     * Description for "from" {identity:"", list:"", field:"", method:"", budget:true, komode:true,}
     * 
     * the group:report should be add the report field like this
     * {id:0, title:"", group:"", equ:"", list:"", reportfields:[] }
     * Description for "reportfields" like the "from" {identity:"", list:"", field:"", method:"", budget:true, komode:true}
     
     */

    public class ReportMaker
    {
        public List<ReportConfig> AllReportConfig { get; set; }
        public SearchEntity ReportContext { get; set; }

        public List<OutputReportItem> InitReportConfig(SearchEntity context, IEnumerator<SPListItem> items)
        {
            DateTime now = DateTime.Now;
            Utilities.Log("[Brochure Report] Start: " + now.ToString());

            ReportContext = context;
            AllReportConfig = new List<ReportConfig>();
            List<OutputReportItem> output = new List<OutputReportItem>();
            int index = 1;
            while (items.MoveNext())
            {
                try
                {
                    AllReportConfig.Add(new ReportConfig(items.Current));
                    Utilities.Log(string.Format("[Brochure Report] Config Round:{0} need:{1}", index, DateTime.Now - now));
                }
                catch (Exception ex)
                {
                    Utilities.Log(string.Format("[Exception] T-ReportConfig title :{0}", items.Current.Title) + ex.Message);
                }
                index++;
            }
             
            AllReportConfig.ForEach(p =>
            {
                output.Add(CreateReport(p, ReportContext));
            });

            Utilities.Log(string.Format("[Brochure Report] Fisish need:{0}", DateTime.Now - now));
            Utilities.Log("[Brochure Report] ======================================");
            return output;
        }

        public List<OutputReportItem> InitReportConfigByGroup(SearchEntity context, string group)
        {
            var items = BusinessService.GetReportConfig(group).GetTypedEnumerator<SPListItem>();
            return InitReportConfig(context, items);
        }


        internal OutputReportItem CreateReport(ReportConfig rc, SearchEntity ReportContext)
        {
            OutputReportItem OPI = new OutputReportItem();
            MappingLocator ML = new MappingLocator(ReportContext);
            DateTime now = DateTime.Now;

            rc.AdditionOutput.ForEach(p =>
            {
                OPI.AdditionOutput.Add(p.Index, LoadAdditionTemplate(p.Template, ReportContext));
            });

            OPI.ExcelTemplate = rc.ExcelTemplate;
            OPI.SheetName = rc.Title;

            rc.GroupMapping.ForEach(group =>
            {
                var rdis = new List<RQDataItem>();
                var GroupMaps = rc.Mapping.Where(p => p.group == group.GroupName).ToList();

                GroupMaps.ForEach(row =>
                {
                    ReportContext.ReportTemplateName = rc.Title + "-" + group.GroupName;

                    RQDataItem rdi = new RQDataItem();
                    row.Datasource = rdis;
                    row.list = row.list.IsNullOrEmpty() ? group.List : row.list;
                    row.digits = row.digits.IsNullOrEmpty() ? "3" : row.digits;
                    rdi = ML.GetMappingRowData(row);
                    rdi.rcol = row.rcol;
                    
                    rdis.Add(rdi);
                });

                OPI.MainDataRow.Add(group, rdis.Where(p => !p.skip).ToList());

                Utilities.Log(string.Format("[Brochure Report] Report :{0} need:{1}", group.GroupName, DateTime.Now - now));

            });
            return OPI;
        }

        private string LoadAdditionTemplate(string p, SearchEntity ReportContext)
        {
            return p.Replace("_CM_", ReportContext.CM).Replace("_Y_", ReportContext.Year + "").Replace("_N_1_", (ReportContext.Year - 1) + "").Replace("_N_2_", (ReportContext.Year - 2) + "")
                .Replace("_M_", ReportContext.Month + "").Replace("_Currency_", ReportContext.LocalCurrency).Replace("_Tonnage_", ReportContext.Toannge).Replace("€", ReportContext.LocalCurrency);
        }
    }



}
